package com.tianma315.core.oss.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;



import com.tianma315.core.common.base.CoreServiceImpl;

import com.tianma315.core.common.config.IFastConfig;
import com.tianma315.core.common.utils.DateUtils;
import com.tianma315.core.common.utils.FileType;
import com.tianma315.core.merchant.service.MerchantService;
import com.tianma315.core.oss.dao.FileDao;
import com.tianma315.core.oss.domain.FileDO;
import com.tianma315.core.oss.sdk.QiNiuOSSService;
import com.tianma315.core.oss.service.FileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



import static org.springframework.cache.interceptor.SimpleKeyGenerator.generateKey;


/**
 * <pre>
 * </pre>
 * 
 * <small> 2018年3月23日 | Aron</small>
 */
@Service
public class FileServiceImpl extends CoreServiceImpl<FileDao, FileDO> implements FileService {

    @Autowired
    private IFastConfig ifastConfig;
    @Autowired
    private QiNiuOSSService qiNiuOSS;
    @Autowired
    private MerchantService merchantService;

    @Override
    public String upload(byte[] uploadBytes, String fileName) {
        fileName = fileName.substring(0, fileName.indexOf(".")) + "-" + System.currentTimeMillis() + fileName.substring(fileName.indexOf("."));
        fileName = ifastConfig.getProjectName() + "/" + DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN_8)
                + "/" + fileName;
        String url = qiNiuOSS.upload(uploadBytes, fileName);
        FileDO sysFile = new FileDO(FileType.fileType(fileName), url, new Date());
        super.insert(sysFile);
        return url;
    }
    @Override
    public String uploadBase64(String baseStr, Integer size) {
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        String uploadBase64 = null;
        try {
            uploadBase64 = qiNiuOSS.uploadBase64(baseStr, size, uuid);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return uploadBase64;
    }
//    @Override
//    public FileDO upload(Long userId, byte[] uploadBytes, String originalFilename) {
//        try {
//            MagicMatch match = null;
//            try {
//                match = Magic.getMagicMatch(uploadBytes, false);
//            } catch (MagicParseException e) {
//                e.printStackTrace();
//            } catch (Exception e) {
//                e.printStackTrace();
//                throw new MessageException("文件解析失败");
//            }
//
//            if (match.getMimeType() == null) {
//                throw new MessageException("系统无法识别当前文件格式");
//            }
//
//            String extension = match.getExtension();
//            String key = String.format("%s%s%s", generateKey(), ".", extension);
//            EntityWrapper<FileDO> wrapper = new EntityWrapper<>();
//            wrapper.eq("file_key", key);
//            //避免key重复
//            while (selectCount(wrapper) > 0) {
//                key = String.format("%s%s%s", generateKey(), ".", extension);
//                wrapper = new EntityWrapper<>();
//                wrapper.eq("file_key", key);
//            }
//            //
//            UploadManager uploadManager = new UploadManager();
//            String token = getQiniuToken();
//            //System.out.println(token);
//            Response response = uploadManager.put(uploadBytes, key, token);
//            PutRet ret = response.jsonToObject(PutRet.class);
//            if (StringUtils.isBlank(ret.key)) {
//                throw new MessageException("文件上传结果解析失败");
//            }
//
//            MerchantDO company = merchantService.getByUserId(userId);
//
//            FileDO fileDO = new FileDO();
//            fileDO.setCompanyId(company.getCompanyId());
//            fileDO.setCreateDate(new Date());
//            fileDO.setType(match.getMimeType());
//            fileDO.setFileKey(key);
//            fileDO.setOriginName(originalFilename);
//            fileDO.setStatus(FileDO.STATUS_ENABLE);
//
//            String host = qiniuConfig().getString(ACCESS_URL);
//            if (!host.endsWith("/")) {
//                host = String.format("%s%s", host, "/");
//            }
//            fileDO.setUrl(String.format("%s%s", host, key));
//            if (!insert(fileDO)) {
//                throw new MessageException("文件存档失败");
//            }
//
//            return fileDO;
//        } catch (QiniuException e) {
//            e.printStackTrace();
//            throw new MessageException(String.format("文件上传失败: %s", responseCode.get(e.response.statusCode)), e);
//        } catch (Throwable e) {
//            throw e;
//        }
//    }
}
